<template>
  <div class="profile-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">个人资料中心</h1>
        <p class="page-description">管理您的账户信息和安全设置</p>
      </div>
      <div class="page-actions">
        <el-button size="large" @click="refreshProfile">
          <el-icon><RefreshRight /></el-icon> 刷新信息
        </el-button>
      </div>
    </div>
    
    <div class="row-container">
      <el-row :gutter="24">
        <!-- 左侧个人信息卡片 -->
        <el-col :md="8" :sm="24">
          <el-card class="profile-info-card" shadow="hover">
            <div class="profile-avatar-container">
              <div class="profile-avatar-wrapper">
                <img :src="adminInfo.avatar || defaultAvatar" class="profile-avatar" alt="管理员头像">
              </div>
              <h2 class="profile-name">{{ adminInfo.admin_name || '-' }}</h2>
              <div class="profile-tags">
                <el-tag type="danger" effect="dark" v-if="adminInfo.admin_level === 0">boss</el-tag>
                <el-tag type="danger" effect="dark" v-else-if="adminInfo.admin_level === 1">超级管理员</el-tag>
                <el-tag effect="dark" v-else>普通管理员</el-tag>
              </div>
            </div>
            
            <!-- 基本信息 -->
            <div class="basic-info-section">
              <div class="section-header">
                <el-icon><User /></el-icon>
                <span class="section-title">基本信息</span>
              </div>
              <div class="info-item">
                <div class="info-label">管理员ID</div>
                <div class="info-value">{{ adminInfo.admin_id || '-' }}</div>
              </div>
              <div class="info-item">
                <div class="info-label">账号等级</div>
                <div class="info-value">
                  <span v-if="adminInfo.admin_level === 0">boss</span>
                  <span v-else-if="adminInfo.admin_level === 1">超级管理员</span>
                  <span v-else>普通管理员</span>
                </div>
              </div>
            </div>
            
            <div class="profile-actions-panel">
              <el-button 
                type="primary" 
                @click="showChangeNameDialog = true" 
                class="new-action-btn"
              >
                修改个人信息
              </el-button>
            </div>
          </el-card>
        </el-col>
        
        <!-- 右侧内容区域 -->
        <el-col :md="16" :sm="24">
          <!-- 最近活动卡片 -->
          <el-card class="activity-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <div class="card-title">
                  <el-icon><Timer /></el-icon> 最近活动
                </div>
              </div>
            </template>
            <div class="activity-container">
              <div v-if="logsLoading" class="logs-loading">
                <el-icon class="is-loading"><Loading /></el-icon>
                <span>加载日志中...</span>
              </div>
              <div v-else-if="recentActivities.length === 0" class="no-logs">
                <el-icon><InfoFilled /></el-icon>
                <span>暂无活动记录</span>
              </div>
              <div v-else class="activity-list-wrapper">
                <div class="activity-item" v-for="(activity, index) in recentActivities" :key="activity.id || index">
                  <div class="activity-icon" :style="{ backgroundColor: activity.color + '20' }">
                    <el-icon><component :is="getActivityIcon(activity.type)" /></el-icon>
                  </div>
                  <div class="activity-content">
                    <div class="activity-info">{{ activity.content }}</div>
                    <div class="activity-time">{{ formatDateTime(activity.time) }}</div>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
          
          <!-- 安全设置卡片 -->
          <el-card class="security-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <div class="card-title">
                  <el-icon><Lock /></el-icon> 安全设置
                </div>
              </div>
            </template>
            <div class="security-settings">
              <div class="security-item">
                <div class="security-info">
                  <div class="security-icon" style="background-color: rgba(24, 144, 255, 0.1)">
                    <el-icon><Key /></el-icon>
                  </div>
                  <div class="security-text">
                    <div class="security-title">账户密码</div>
                    <div class="security-desc">定期修改密码可以保护账户安全</div>
                  </div>
                </div>
                <div class="security-btn-container">
                  <el-button 
                    size="default" 
                    type="primary" 
                    @click="showChangePwd = true" 
                    class="security-action-btn"
                  >
                    修改密码
                  </el-button>
                </div>
              </div>
              
              <el-divider v-if="adminInfo.admin_level === 1"></el-divider>
              
              <div class="security-item" v-if="adminInfo.admin_level === 0 || adminInfo.admin_level === 1">
                <div class="security-info">
                  <div class="security-icon" style="background-color: rgba(82, 196, 26, 0.1)">
                    <el-icon><Plus /></el-icon>
                  </div>
                  <div class="security-text">
                    <div class="security-title">管理员账号管理</div>
                    <div class="security-desc">创建或管理管理员账号</div>
                  </div>
                </div>
                <div class="security-btn-container">
                  <el-button size="default" type="success" @click="navigateToAdminList" class="security-action-btn security-action-btn-success">
                    前往管理
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 修改个人信息对话框 -->
    <el-dialog title="修改个人信息" v-model="showChangeNameDialog" width="400px" custom-class="pwd-dialog">
      <el-form :model="nameForm" :rules="nameRules" ref="nameFormRef" label-width="80px">
        <el-form-item label="新用户名" prop="newName">
          <el-input v-model="nameForm.newName" autocomplete="off">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="密码验证" prop="password">
          <el-input v-model="nameForm.password" type="password" autocomplete="off" show-password>
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showChangeNameDialog = false" class="dialog-btn dialog-btn-cancel">取消</el-button>
          <el-button type="primary" @click="submitChangeName" class="dialog-btn dialog-btn-confirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" v-model="showChangePwd" width="400px" custom-class="pwd-dialog">
      <el-form :model="pwdForm" :rules="pwdRules" ref="pwdFormRef" label-width="80px">
        <el-form-item label="原密码" prop="oldPwd">
          <el-input v-model="pwdForm.oldPwd" type="password" autocomplete="off">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input v-model="pwdForm.newPwd" type="password" autocomplete="off" show-password>
            <template #prefix>
              <el-icon><Key /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPwd">
          <el-input v-model="pwdForm.confirmPwd" type="password" autocomplete="off" show-password>
            <template #prefix>
              <el-icon><Check /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showChangePwd = false" class="dialog-btn dialog-btn-cancel">取消</el-button>
          <el-button type="primary" @click="submitChangePwd" class="dialog-btn dialog-btn-confirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 浮动操作区 -->
    <div class="floating-actions">
      <el-button type="primary" @click="refreshProfile" class="refresh-btn">
        <el-icon><RefreshRight /></el-icon>
      </el-button>
    </div>
    
    <!-- 底部安全区域 -->
    <div class="bottom-safe-area"></div>
  </div>
</template>

<script>
import axios from 'axios'
import { 
  RefreshRight, 
  User, 
  Lock, 
  Key, 
  Check, 
  Plus, 
  Timer,
  Monitor,
  Tools,
  Warning,
  Document,
  Loading,
  InfoFilled,
  Delete
} from '@element-plus/icons-vue'

export default {
  name: 'AdminProfile',
  components: {
    RefreshRight,
    User,
    Lock,
    Key,
    Check,
    Plus,
    Timer,
    Monitor,
    Tools,
    Warning,
    Document,
    Loading,
    InfoFilled,
    Delete
  },
  data() {
    return {
      adminInfo: {
        admin_name: '',
        admin_level: 1,
        create_time: '',
        avatar: '',
        phone: '',
        email: ''
      },
      defaultAvatar: '',
      showChangePwd: false,
      showChangeNameDialog: false,
      nameForm: {
        newName: '',
        password: ''
      },
      nameRules: {
        newName: [
          { required: true, message: '请输入新用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码验证', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ]
      },
      pwdForm: {
        oldPwd: '',
        newPwd: '',
        confirmPwd: ''
      },
      pwdRules: {
        oldPwd: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        newPwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPwd: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: (rule, value) => {
            if (value !== this.pwdForm.newPwd) {
              return Promise.reject('两次输入的密码不一致');
            }
            return Promise.resolve();
          }, trigger: 'blur' }
        ]
      },
      // 将recentActivities初始化为空数组，后续从API获取
      loginDays: 0,
      deviceCount: 0,
      taskCount: 0,
      lastLogin: '',
      recentActivities: [],
      // 添加日志加载状态
      logsLoading: false,
      // 添加日志分页相关数据
      logsPageSize: 100,
      logsCurrentPage: 1,
      logsTotal: 0,
      // 添加日志自动刷新定时器
      logRefreshTimer: null,
      // 日志自动刷新间隔（毫秒）
      logRefreshInterval: 60000 // 1分钟刷新一次
    }
  },
  created() {
    // 从localStorage获取管理员信息
    const adminInfoStr = localStorage.getItem('adminInfo');
    if (adminInfoStr) {
      try {
        const adminInfo = JSON.parse(adminInfoStr);
        this.adminInfo = {
          ...this.adminInfo,
          ...adminInfo
        };
      } catch (error) {
        console.error('解析管理员信息失败:', error);
      }
    }
    
    // 检查全局axios是否存在
    if (!this.$axios) {
      console.error('警告: $axios 未定义，请确保已正确配置axios')
    }
    
    // 尝试从localStorage加载已保存的日志
    const savedLogs = localStorage.getItem('adminLogs');
    const savedTimestamp = localStorage.getItem('adminLogsTimestamp');
    
    if (savedLogs && savedTimestamp) {
      try {
        // 检查日志是否过期（超过30分钟就重新加载）
        const currentTime = new Date().getTime();
        const savedTime = parseInt(savedTimestamp);
        const timeElapsed = currentTime - savedTime;
        
        // 如果日志保存时间不超过30分钟，直接使用缓存
        if (timeElapsed < 30 * 60 * 1000) {
          const logs = JSON.parse(savedLogs);
          this.logsTotal = logs.length;
          
          // 在这里也应用去重逻辑
          const activitiesWithoutDuplicates = this.convertLogsToActivities(logs);
          this.recentActivities = activitiesWithoutDuplicates;
          
          // 更新最后登录时间（如果有）
          const loginLogs = logs.filter(log => 
            log.operation === 'login' || 
            (log.path && log.path === '/api/v1/admin/login') || 
            (log.path && log.path === '/api/admin/v1/login'));
          
          if (loginLogs.length > 0) {
            this.lastLogin = loginLogs[0].timestamp;
          }
          
          console.log('从缓存加载日志记录:', this.recentActivities.length);
        } else {
          // 缓存过期，重新加载
          this.loadAdminLogs();
        }
      } catch (error) {
        console.error('解析保存的日志失败:', error);
        this.loadAdminLogs();
      }
    } else {
      // 没有缓存，加载管理员日志
      this.loadAdminLogs();
    }
    
    // 启动日志自动刷新
    this.startLogRefresh();
  },
  beforeUnmount() {
    // 组件销毁前清除定时器
    this.stopLogRefresh();
  },
  methods: {
    // 添加加载管理员日志的方法
    loadAdminLogs() {
      this.logsLoading = true;
      this.logsCurrentPage = 1; // 重置为第一页
      
      // 请求管理员日志API
      // 支持两种API路径格式
      axios.get(`https://smartsound.top/api/v1/admin/get_my_logs?page_size=${this.logsPageSize}`)
        .then(response => {
          if (response.data && response.data.code === 0) {
            const logsData = response.data.data;
            
            // 过滤掉查看自己日志的操作
            const filteredLogs = logsData.logs.filter(log => {
              // 只排除查看自己日志的操作
              if (log.operation === 'query_self_logs' || 
                  (log.path && log.path.includes('/api/v1/admin/get_my_logs')) ||
                  (log.path && log.path.includes('/api/admin/v1/get_my_logs'))) {
                return false;
              }
              return true;
            });
            
            // 保存总数量
            this.logsTotal = filteredLogs.length;
            
            // 更新最后登录时间（如果有）
            const loginLogs = filteredLogs.filter(log => 
              log.operation === 'login' || 
              (log.path && log.path === '/api/v1/admin/login') || 
              (log.path && log.path === '/api/admin/v1/login'));
            
            if (loginLogs.length > 0) {
              this.lastLogin = loginLogs[0].timestamp;
            }
            
            // 转换日志为活动格式
            this.recentActivities = this.convertLogsToActivities(filteredLogs);
            
            // 将日志数据保存到localStorage，确保页面切换后不丢失
            localStorage.setItem('adminLogs', JSON.stringify(filteredLogs));
            localStorage.setItem('adminLogsTimestamp', new Date().getTime().toString());
          } else {
            console.error('获取管理员日志失败:', response.data.message);
            this.$message.error('获取日志失败: ' + response.data.message);
          }
        })
        .catch(error => {
          console.error('获取管理员日志错误:', error);
          this.$message.error('获取日志失败，请稍后重试');
        })
        .finally(() => {
          this.logsLoading = false;
        });
    },
    
    // 将日志转换为活动格式的方法
    convertLogsToActivities(logs) {
      // 获取全部日志
      const recentLogs = logs;
      
      // 对日志进行去重处理，同一操作在短时间内(5秒)只保留一条
      const deduplicatedLogs = [];
      const operationTimeMap = new Map(); // 用于存储操作类型和时间
      
      // 按时间降序排序，确保保留最新的记录
      const sortedLogs = [...recentLogs].sort((a, b) => {
        const timeA = new Date(a.timestamp).getTime();
        const timeB = new Date(b.timestamp).getTime();
        return timeB - timeA; // 降序排序
      });
      
      sortedLogs.forEach(log => {
        // 处理特殊的 toggle_active API 调用，映射到 ban_admin 或 unban_admin
        if (log.path && log.path.includes('/api/v1/admin/toggle_active')) {
          // 根据操作细节判断是 ban 还是 unban
          if (log.details && log.details.action === 'activate') {
            log.operation = 'unban_admin';
          } else if (log.details && log.details.action === 'deactivate') {
            log.operation = 'ban_admin';
          } else {
            // 如果没有详细信息，尝试从内容判断
            if (log.content && log.content.includes('解禁')) {
              log.operation = 'unban_admin';
            } else if (log.content && log.content.includes('禁用')) {
              log.operation = 'ban_admin';
            }
            // 操作失败的情况
            else if (log.status === 'failed' || log.error) {
              log.operation = 'toggle_admin_active';
            }
          }
        }
        
        // 处理查看用户详情的API调用
        if (log.path && log.path.includes('/api/v1/admin/userdetail')) {
          log.operation = 'query_user_detail';
          log.resource_type = 'users';
        }
        
        // 处理获取设备状态的API调用
        if (log.path && log.path.includes('/api/v1/admin/devices/status')) {
          log.operation = 'get_device_status_stats';
          log.resource_type = 'devices';
        }
        
        // 处理更新反馈状态的API调用
        if (log.path && log.path.includes('/api/admin/feedback/v1/update_status') || 
            log.path && log.path.includes('/api/v1/feedback/update_status')) {
          log.operation = 'update_feedback_status';
          log.resource_type = 'feedback';
        }
        
        // 为每个操作创建唯一标识
        // 对于相同资源的相同操作类型认为是重复操作
        // 将禁用和解禁管理员的操作进行特殊处理
        let operationKey;
        
        // 对于禁用或解禁账号，忽略操作来源，只考虑被操作的管理员ID
        if (log.operation === 'ban_admin' || log.operation === 'unban_admin') {
          // 如果有详细信息中包含admin_id，使用它作为唯一标识
          const targetAdminId = log.details?.admin_id || log.details?.target_admin_id || '';
          operationKey = `admin_status_change_${targetAdminId}`;
        } else {
          // 其他操作保持原有的唯一标识方式
          operationKey = `${log.operation}_${log.resource_type || ''}_${log.path || ''}`;
        }
        
        const currentTime = new Date(log.timestamp).getTime();
        
        // 检查是否已存在相同操作，且时间相差小于5秒
        const existingTime = operationTimeMap.get(operationKey);
        if (existingTime && Math.abs(currentTime - existingTime) < 5000) {
          // 跳过这条日志，不添加到去重结果中
          return;
        }
        
        // 记录这个操作和时间
        operationTimeMap.set(operationKey, currentTime);
        deduplicatedLogs.push(log);
      });
      
      // 使用去重后的日志
      return deduplicatedLogs.map(log => {
        // 统一register_admin为add_admin（可选）
        // if (log.operation === 'register_admin') {
        //   log.operation = 'add_admin';
        // }
        let type = 'info';
        let color = '#909399';
        let content = '';

        // 特殊处理 log_activity 路径
        if (log.path && log.path.includes('/api/v1/admin/log_activity')) {
          return {
            id: log._id,
            type: 'info',
            color: '#909399',
            content: '查询管理员日志',
            time: log.timestamp,
            details: log.details
          };
        }

        switch(log.operation) {
          case 'login':
            type = 'primary';
            color = '#409EFF';
            content = '登录系统';
            break;
          case 'get_announcements':
            type = 'info';
            color = '#909399';
            content = '查询公告列表';
            break;
          case 'get_feedback_replies':
            type = 'info';
            color = '#909399';
            content = '查看反馈回复';
            break;
          case 'query_user_detail':
            type = 'info';
            color = '#909399';
            content = '查看用户详情';
            break;
          case 'get_device_status_stats':
            type = 'info';
            color = '#909399';
            content = '获取设备状态';
            break;
          case 'update_feedback_status':
            type = 'success';
            color = '#67C23A';
            content = '更新反馈状态';
            break;
          case 'change_authority':
            type = 'success';
            color = '#67C23A';
            content = '修改管理员权限';
            break;
          case 'change_admin_name':
            type = 'success';
            color = '#67C23A';
            content = '修改个人信息';
            break;
          case 'ban_admin':
            type = 'warning';
            color = '#E6A23C';
            content = '禁用账号';
            break;
          case 'unban_admin':
            type = 'success';
            color = '#67C23A';
            content = '解禁账号';
            break;
          case 'toggle_admin_active':
            type = 'danger';
            color = '#F56C6C';
            content = '修改管理员账户状态失败';
            break;
          case 'query':
          case 'query_user_activity':
          case 'query_device_activity':
          case 'query_listening_distribution':
          case 'query_music_overview':
          case 'query_admin_list':
          case 'query_self_logs':
          case 'query_admin_logs':
          case 'list_feedback':
            type = 'info';
            color = '#909399';
            content = this.getQueryDescription(log);
            break;
          case 'update':
          case 'changepassword':
          case 'change_password':
            type = 'success';
            color = '#67C23A';
            content = '修改密码';
            break;
          case 'register_admin':
            type = log.status === 'success' ? 'success' : 'danger';
            color = log.status === 'success' ? '#67C23A' : '#F56C6C';
            content = log.status === 'success'
              ? `创建管理员 ${log.details?.new_admin_name || ''}`
              : `创建管理员失败: ${log.details?.error || '未知错误'}`;
            break;
          case 'delete_admin':
            if (log.details && (log.details.target_admin_name || (log.details.deleted_admin && log.details.deleted_admin.admin_name))) {
              type = 'danger';
              color = '#F56C6C';
              const name = log.details.target_admin_name || (log.details.deleted_admin && log.details.deleted_admin.admin_name) || '';
              content = `删除管理员 ${name}`;
            } else {
              return null; // 无详细信息的过滤掉
            }
            break;
          case 'add_admin':
            type = log.status === 'success' ? 'success' : 'danger';
            color = log.status === 'success' ? '#67C23A' : '#F56C6C';
            content = log.status === 'success' 
              ? `创建管理员 ${log.details?.new_admin_name || ''}`
              : `创建管理员失败: ${log.details?.error || '未知错误'}`;
            break;
          case 'reply_feedback':
            type = 'success';
            color = '#67C23A';
            content = `回复了用户${log.details?.user_id || ''}的反馈`;
            break;
          case 'delete_user':
            type = 'danger';
            color = '#F56C6C';
            content = '删除用户';
            break;
          case 'delete_device':
            type = 'danger';
            color = '#F56C6C';
            content = '删除设备';
            break;
          case 'add_device':
            type = 'success';
            color = '#67C23A';
            content = '添加设备';
            break;
          case 'delete':
            type = 'danger';
            color = '#F56C6C';
            content = '删除操作';
            break;
          default:
            content = `${log.operation} ${log.path ? `(${log.path})` : ''}`;
        }
        
        // 特别处理密码修改操作
        if (log.operation === 'change_password' || log.operation === 'changepassword') {
          content = '修改密码';
        }
        return {
          id: log._id,
          type,
          color,
          content,
          time: log.timestamp,
          details: log.details
        };
      }).filter(item => item !== null);
    },
    
    // 获取查询操作的描述
    getQueryDescription(log) {
      switch(log.resource_type) {
        case 'users':
          // 特殊处理用户详情查询
          if (log.path && log.path.includes('/api/v1/admin/userdetail')) {
            return '查看用户详情';
          }
          return '查询用户数据';
        case 'devices':
          // 特殊处理设备状态查询
          if (log.path && log.path.includes('/api/v1/admin/devices/status')) {
            return '获取设备状态';
          }
          return '查询设备数据';
        case 'statistics':
          if (log.path && log.path.includes('user_activity')) {
            return '查询用户活跃度数据';
          } else if (log.path && log.path.includes('device_activity')) {
            return '查询设备活跃度数据';
          } else if (log.path && log.path.includes('listening_time')) {
            return '查询听歌时段分布';
          } else if (log.path && log.path.includes('music_overview')) {
            return '查询音乐播放概览';
          }
          return '查询统计数据';
        case 'admins':
          return '查询管理员列表';
        case 'admin_logs':
          return '查询管理员日志';
        case 'feedback':
          // 特殊处理更新反馈状态
          if (log.path && (log.path.includes('/api/admin/feedback/v1/update_status') || 
                          log.path.includes('/api/v1/feedback/update_status'))) {
            return '更新反馈状态';
          }
          return '查询用户反馈';
        case 'announcements':
          return '查询公告列表';
        default:
          // 特殊处理 query_admin_logs 操作
          if (log.operation === 'query_admin_logs' || (log.path && log.path.includes('/api/v1/admin/log_activity'))) {
            return '查询管理员日志';
          }
          // 特殊处理 get_feedback_replies 操作
          if (log.operation === 'get_feedback_replies' || (log.path && log.path.includes('/api/v1/feedback/replies'))) {
            return '查看反馈回复';
          }
          return `查询${log.resource_type || '数据'}`;
      }
    },
    
    submitChangeName() {
      this.$refs.nameFormRef.validate(valid => {
        if (!valid) return
        
        // 调用后端修改用户名接口
        const requestData = {
          new_admin_name: this.nameForm.newName,
          admin_password: this.nameForm.password
        };
        
        axios.post('https://smartsound.top/api/v1/admin/change_name', requestData)
          .then(response => {
            if (response.data && response.data.code === 0) {
              this.$message.success('用户名修改成功');
              
              // 更新本地存储的管理员信息
              const adminInfoStr = localStorage.getItem('adminInfo');
              if (adminInfoStr) {
                try {
                  const adminInfo = JSON.parse(adminInfoStr);
                  adminInfo.admin_name = this.nameForm.newName;
                  localStorage.setItem('adminInfo', JSON.stringify(adminInfo));
                  
                  // 更新页面上的显示
                  this.adminInfo.admin_name = this.nameForm.newName;
                } catch (error) {
                  console.error('更新本地管理员信息失败:', error);
                }
              }
              
              this.showChangeNameDialog = false;
              // 重置表单
              this.resetNameForm();
            } else {
              throw new Error(response.data.message || '用户名修改失败');
            }
          })
          .catch(error => {
            console.error('用户名修改失败:', error);
            this.$message.error('操作失败: ' + (error.message || '未知错误'));
          });
      });
    },
    
    // 重置用户名表单
    resetNameForm() {
      this.nameForm = {
        newName: '',
        password: ''
      };
      
      // 如果表单已经挂载，则重置验证状态
      if (this.$refs.nameFormRef) {
        this.$refs.nameFormRef.resetFields();
      }
    },
    
    submitChangePwd() {
      this.$refs.pwdFormRef.validate(valid => {
        if (!valid) return
        
        // 调用后端修改密码接口
        const requestData = {
          admin_name: this.adminInfo.admin_name,
          current_password: this.pwdForm.oldPwd,
          new_password: this.pwdForm.newPwd
        };
        
        axios.post('https://smartsound.top/api/v1/admin/changepassword', requestData)
          .then(response => {
            if (response.data && response.data.code === 0) {
              this.$message.success('密码修改成功');
              
              // 更新本地存储的管理员信息
              const adminInfoStr = localStorage.getItem('adminInfo');
              if (adminInfoStr) {
                try {
                  const adminInfo = JSON.parse(adminInfoStr);
                  adminInfo.admin_password = this.pwdForm.newPwd;
                  localStorage.setItem('adminInfo', JSON.stringify(adminInfo));
                  
                  // 更新页面上的显示
                  this.adminInfo.admin_password = this.pwdForm.newPwd;
                } catch (error) {
                  console.error('更新本地管理员信息失败:', error);
                }
              }
              
              this.showChangePwd = false;
              // 重置表单
              this.resetPwdForm();
            } else {
              throw new Error(response.data.message || '密码修改失败');
            }
          })
          .catch(error => {
            console.error('密码修改失败:', error);
            this.$message.error('操作失败: ' + (error.message || '未知错误'));
          });
      });
    },
    
    // 重置密码表单
    resetPwdForm() {
      this.pwdForm = {
        oldPwd: '',
        newPwd: '',
        confirmPwd: ''
      };
      
      // 如果表单已经挂载，则重置验证状态
      if (this.$refs.pwdFormRef) {
        this.$refs.pwdFormRef.resetFields();
      }
    },
    
    navigateToAdminList() {
      // 实现跳转到管理员列表页面的逻辑
      console.log('跳转到管理员列表页面');
      this.$router.push('/admin');
    },
    getActivityIcon(type) {
      const iconMap = {
        'primary': 'Monitor',
        'success': 'Tools',
        'warning': 'Warning',
        'info': 'Document',
        'danger': 'Delete'
      };
      return iconMap[type] || 'Timer';
    },
    refreshProfile() {
      this.loadAdminLogs();
      this.$message.success('刷新个人信息成功');
    },
    // 启动日志自动刷新
    startLogRefresh() {
      this.logRefreshTimer = setInterval(() => {
        this.loadAdminLogs();
      }, this.logRefreshInterval);
    },
    // 停止日志自动刷新
    stopLogRefresh() {
      clearInterval(this.logRefreshTimer);
    },
    formatDateTime(timestamp) {
      if (!timestamp) return '';
      
      try {
        const date = new Date(timestamp);
        if (isNaN(date.getTime())) return timestamp; // If invalid date, return the original
        
        // Format: YYYY-MM-DD HH:MM:SS
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');
        
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      } catch (error) {
        console.error('日期格式化错误:', error);
        return timestamp; // Return original on error
      }
    }
  }
}
</script>

<style scoped>
.profile-container {
  padding: 16px 5px;
  position: relative;
  margin-bottom: 80px;
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #1890ff, #722ed1);
  color: white;
  border-radius: 12px;
  padding: 32px 40px;
  margin-bottom: 35px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: relative;
}

.page-header::after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 50%;
  background: rgba(255, 255, 255, 0.1);
  transform: skewX(-20deg);
}

.header-content {
  z-index: 1;
}

.page-title {
  font-size: 28px;
  margin: 0 0 12px 0;
  font-weight: 600;
}

.page-description {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
  line-height: 1.6;
}

.page-actions {
  z-index: 1;
  display: flex;
  gap: 10px;
}

/* 行容器样式 */
.row-container {
  margin-bottom: 30px;
  position: relative;
  z-index: 0;
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 添加flex布局使列对齐 */
.el-row {
  display: flex;
  flex-wrap: wrap;
}

.el-row .el-col {
  display: flex;
  flex-direction: column;
}

/* 卡片基本样式 */
.el-card {
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.03);
  transform: translate3d(0, 0, 0);
  will-change: transform;
  transition: all 0.3s;
  margin-bottom: 24px;
  overflow: hidden;
  height: 100%; /* 设置卡片高度为100% */
  display: flex;
  flex-direction: column;
}

.el-card:hover {
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
  z-index: 1;
  border-color: rgba(24, 144, 255, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 头像样式 */
.profile-avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
  flex-shrink: 0; /* 防止容器收缩 */
}

.profile-avatar-wrapper {
  position: relative;
  width: 120px;
  height: 120px;
  margin-bottom: 16px;
}

.profile-avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.profile-name {
  font-size: 22px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #303133;
}

.profile-tags {
  margin-bottom: 8px;
}

/* 基本信息样式 */
.basic-info-section {
  margin-bottom: 24px;
  flex: 1; /* 允许该部分占据剩余空间 */
  overflow-y: auto; /* 内容过多时添加滚动 */
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  gap: 8px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.info-item {
  display: flex;
  margin-bottom: 12px;
  align-items: baseline;
}

.info-label {
  width: 80px;
  color: #909399;
  font-size: 14px;
  flex-shrink: 0;
}

.info-value {
  flex: 1;
  color: #303133;
  font-size: 14px;
  word-break: break-all;
}

/* 操作按钮 */
.profile-actions-panel {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: auto; /* 将按钮推到底部 */
  flex-shrink: 0; /* 防止按钮部分收缩 */
}

.new-action-btn {
  width: 100%;
  height: 44px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
  background: linear-gradient(135deg, #1890ff, #0050b3);
  border: none;
  color: white;
  box-shadow: 0 4px 10px rgba(24, 144, 255, 0.3);
  transition: all 0.3s;
}

.new-action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(24, 144, 255, 0.4);
  background: linear-gradient(135deg, #40a9ff, #096dd9);
}

.new-action-btn:active {
  transform: translateY(1px);
  box-shadow: 0 2px 5px rgba(24, 144, 255, 0.3);
}

/* 活动列表样式 */
.activity-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;
}

.activity-list-wrapper {
  max-height: 400px;
  overflow-y: auto;
  padding-right: 8px;
  margin-right: -8px; /* 补偿padding-right */
}

.logs-loading, .no-logs {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #909399;
}

.logs-loading i, .no-logs i {
  font-size: 32px;
  margin-bottom: 12px;
}

.activity-item {
  display: flex;
  align-items: flex-start;
  padding: 16px;
  border-radius: 8px;
  background-color: #f9f9f9;
  transition: all 0.3s;
}

.activity-item:hover {
  background-color: #f0f7ff;
  transform: translateX(5px);
}

.activity-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  flex-shrink: 0;
}

.activity-content {
  flex: 1;
}

.activity-info {
  font-size: 15px;
  color: #303133;
  margin-bottom: 4px;
}

.activity-time {
  font-size: 13px;
  color: #909399;
}

/* 安全设置样式 */
.security-settings {
  display: flex;
  flex-direction: column;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  margin-bottom: 16px;
  border-radius: 8px;
  background-color: #f9f9f9;
  transition: background-color 0.3s;
}

.security-item:hover {
  background-color: #f0f7ff;
}

.security-btn-container {
  min-width: 120px;
  display: flex;
  justify-content: center;
  width: 120px;
}

.security-action-btn {
  min-width: 120px;
  height: 40px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  background-color: #1890ff;
  border: none;
  color: white;
  box-shadow: 0 3px 8px rgba(24, 144, 255, 0.2);
  transition: all 0.3s;
}

.security-action-btn:hover {
  background-color: #40a9ff;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.security-action-btn:active {
  background-color: #096dd9;
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.2);
}

.security-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.security-text {
  display: block;
  flex: 1;
}

.security-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  flex-shrink: 0;
}

.security-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.security-desc {
  font-size: 13px;
  color: #909399;
  display: block !important;
  visibility: visible !important;
  opacity: 1 !important;
}

/* 浮动操作区 */
.floating-actions {
  position: fixed;
  right: 24px;
  bottom: 24px;
  display: flex;
  align-items: center;
  z-index: 100;
}

.refresh-btn {
  margin-left: 0;
}

/* 底部安全区域 */
.bottom-safe-area {
  height: 60px;
  width: 100%;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    padding: 24px;
  }
  
  .page-actions {
    margin-top: 20px;
    flex-wrap: wrap;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .profile-avatar {
    width: 100px;
    height: 100px;
  }
  
  .profile-avatar-wrapper {
    width: 100px;
    height: 100px;
  }
  
  .profile-name {
    font-size: 20px;
  }
  
  .floating-actions {
    right: 16px;
    bottom: 16px;
  }
}

/* 添加成功类型按钮的样式 */
.security-action-btn-success {
  background-color: #52c41a;
  box-shadow: 0 3px 8px rgba(82, 196, 26, 0.2);
}

.security-action-btn-success:hover {
  background-color: #73d13d;
  box-shadow: 0 4px 12px rgba(82, 196, 26, 0.3);
}

.security-action-btn-success:active {
  background-color: #389e0d;
  box-shadow: 0 2px 4px rgba(82, 196, 26, 0.2);
}

/* 对话框按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.dialog-btn {
  min-width: 90px;
  height: 40px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
}

.dialog-btn-cancel {
  color: #606266;
  background: #f5f7fa;
  border-color: #dcdfe6;
}

.dialog-btn-cancel:hover {
  background: #e9ecf2;
  color: #409eff;
}

.dialog-btn-confirm {
  background: linear-gradient(135deg, #1890ff, #0050b3);
  border: none;
  color: white;
  box-shadow: 0 3px 8px rgba(24, 144, 255, 0.2);
}

.dialog-btn-confirm:hover {
  background: linear-gradient(135deg, #40a9ff, #096dd9);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.dialog-btn-confirm:active {
  background: linear-gradient(135deg, #096dd9, #003a8c);
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.2);
}

/* 对话框样式 */
:deep(.pwd-dialog), :deep(.register-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.pwd-dialog .el-dialog__header), :deep(.register-dialog .el-dialog__header) {
  background: linear-gradient(135deg, #1890ff, #0050b3);
  padding: 16px 20px;
}

:deep(.pwd-dialog .el-dialog__title), :deep(.register-dialog .el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.pwd-dialog .el-dialog__headerbtn .el-dialog__close), 
:deep(.register-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: rgba(255, 255, 255, 0.9);
}
</style>